package org.example.uhy.domain.model.upgrade.execution.node;

import org.example.uhy.domain.model.member.MemberId;
import org.example.uhy.domain.model.upgrade.execution.UpgradeExecutionContext;

import java.math.BigDecimal;
import java.util.List;

public class TradeMoneyRuleExecutionNode extends ConditionUpgradeExecutionNode<BigDecimal> {
    public static final String TYPE = "TRADE_SUM";

    public TradeMoneyRuleExecutionNode(BigDecimal expectedValue) {
        super(expectedValue);
    }

    @Override
    public boolean match(UpgradeExecutionContext context) {
        BigDecimal accSum = getAccumulationTradeMoney(context);
        if (accSum == null || accSum.equals(BigDecimal.ZERO)) {
            return false;
        }
        return accSum.compareTo(getExpectedValue()) >= 0;
    }


    private BigDecimal getAccumulationTradeMoney(UpgradeExecutionContext context) {
        if (context.hasCachedValue(TYPE)) {
            return context.getCachedValue(TYPE);
        }
        BigDecimal accumulationTradeMoney = BigDecimal.ZERO;
        if (context.upgradeObject().isMember()) {
            accumulationTradeMoney = context.tradeRepository().accumulationMoneyOfMember(context.upgradeObject().memberId());
        } else {
            List<MemberId> memberIds = membersOfContributor(context);
            if (memberIds != null && memberIds.size() > 0) {
                accumulationTradeMoney = context.tradeRepository().accumulationMoneyOfMembers(memberIds);
            }
        }
        context.setCachedValue(TYPE, accumulationTradeMoney);
        return accumulationTradeMoney;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}